package com.bestcem.xm.ticket.service.manager.role;

import com.bestcem.xm.ticket.entity.mongo.TicketFlow;
import com.bestcem.xm.ticket.enums.RoleTimeLimitTypeEnum;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

import static com.bestcem.xm.common.core.uitls.DateUtil.BEIJING_ZONE;

/**
 * 工单规则 跟进人/审核人 信息工具类基类
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/17 18:26
 */
@ToString(callSuper = true)
@NoArgsConstructor
@Getter
public abstract class BaseTicketRole {
    /**
     * region
     */
    private String region;
    /**
     * roleId
     */
    private String roleId;
    /**
     * timeLimit
     */
    private Integer timeLimit;
    /**
     * timeLimitType
     */
    private Integer timeLimitType;
    /**
     * deadline
     */
    private Date deadline;


    protected BaseTicketRole(TicketFlow.FollowConfig config) {
        if (Objects.isNull(config)) {
            return;
        }
        this.region = config.getRegion();
        this.roleId = config.getRoleId();
        String timeLimit = config.getTimeLimit();
        if (ObjectUtils.isEmpty(timeLimit)) {
            timeLimit = "0";
        }
        this.timeLimit = Integer.parseInt(timeLimit, 10);
        this.timeLimitType = config.getTimeLimitType();
        if (hasLimit()) {
            this.deadline = getInitDeadline();
        }
    }

    private boolean hasLimit() {
        if (Objects.isNull(this.timeLimit) || Objects.isNull(this.timeLimitType)) {
            return false;
        }
        return (this.timeLimit != 0 && this.timeLimitType != 0);
    }

    private Date getInitDeadline() {
        if (!hasLimit()) {
            return null;
        }
        Date result = null;
        if (RoleTimeLimitTypeEnum.HOUR.getIndex() == this.timeLimitType) {
            result = Date.from(LocalDateTime.now().plusHours(this.timeLimit).toInstant(BEIJING_ZONE));
        }
        if (RoleTimeLimitTypeEnum.DAY.getIndex() == this.timeLimitType) {
            result = Date.from(LocalDateTime.now().plusDays(this.timeLimit).toInstant(BEIJING_ZONE));
        }
        return result;
    }


}
